package com.secure.message;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * json消息转换器重写
 *
 * @author 12556
 */
public class JsonMessageConverter extends MappingJackson2HttpMessageConverter implements WebMvcConfigurer {

    @Override
    public Charset getDefaultCharset() {
        return StandardCharsets.UTF_8;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON);
        return list;
    }

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //解决响应加密成字符串，jackson依旧转化为json格式，导致字符串带双引号问题
        if (object instanceof String) {
            StreamUtils.copy((String) object, this.getDefaultCharset(), outputMessage.getBody());
        } else {
            super.writeInternal(object, type, outputMessage);
        }
    }

    /**
     * 把自己加入消息转换器列表
     *
     * @param converters 消息转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(this);
    }
}